<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="产品名称">
                <a-input v-model="queryParam.search_product_name_key" placeholder="请输入产品名称" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="操作员名称">
                <a-input v-model="queryParam.search_process_user_name_key" placeholder="请输入操作员名称" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="批次名称">
                <a-input v-model="queryParam.search_batch_name_key" placeholder="请输入批次名称" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="批次编号">
                <a-input v-model="queryParam.search_batch_number_key" placeholder="请输入批次编号" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="创建时间">
                <a-config-provider :locale="locale">
                  <a-range-picker
                    format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    @change="onChange"
                    @calendarChange="calendarChange"
                    :ranges="ranges"
                  />
                </a-config-provider>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="$refs.table.refresh(true)" type="primary">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.search_state" @change="onOptionChange">
          <a-radio-button :value="-1"> 全部 </a-radio-button>
          <a-radio-button :value="1"> 已提交 </a-radio-button>
          <a-radio-button :value="0"> 未提交 </a-radio-button>
        </a-radio-group>
        <div>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="allChangeStatus('delete')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>
      <a-alert
        :message="`已选择 ${selectedRowKeys.length} 项`"
        v-if="selectedRowKeys.length"
        type="info"
        style="margin-bottom: 16px"
        show-icon
      />

      <s-table
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        rowKey="id"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <a-popconfirm
          placement="topLeft"
          slot="is_show"
          slot-scope="text, record"
          ok-text="确定"
          cancel-text="取消"
          @confirm="changeShow(record)"
        >
          <template slot="title">
            <p>{{ text == 0 ? '是否确定启用' : '是否确定禁用' }}</p>
          </template>
          <a-switch checked-children="开" un-checked-children="关" :checked="text == 1" />
        </a-popconfirm>

        <div slot="state_status" slot-scope="text">
          <div v-if="text == 0" class="coupon-status-1">未提交</div>
          <div v-if="text == 1" class="coupon-status-1">已提交</div>
        </div>

        <span slot="updated_at" slot-scope="text">{{ text | timeFormat }}</span>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">查看</a-button>
          <a-divider type="vertical" />
          <!-- <a-popconfirm title="确认删除该产品吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm> -->
          <a-dropdown>
            <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="handleDelete(record)">删除</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </s-table>

      <a-modal
        :title="'溯源详情'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <div>{{ name }}的溯源1</div>
        <div v-for="(item, index) in log_sheet_list" :key="index">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="item.key" hasFeedback>
            <div v-if="item.type == 'checkbox'">
              <span v-for="(checkbox_item, checkbox_index) in item.value" :key="checkbox_index">
                {{ checkbox_item }}
              </span>
            </div>
            <div v-else-if="item.type == 'uploadImg'">
              <span v-if="item.value.length">
                <img
                  class="img"
                  :src="img_item"
                  alt=""
                  v-for="(img_item, img_index) in item.value"
                  :key="img_index"
                  @click="seeImg(img_item)"
                />
              </span>
            </div>
            <div v-else-if="item.type == 'uploadVideo'">
              <span v-if="item.value.length">
                <video
                  class="video"
                  v-for="(video_item, video_index) in item.value"
                  :key="video_index"
                  :src="video_item"
                  controls
                ></video>
              </span>
            </div>
            <div v-else>
              {{ item.value }}
            </div>
          </a-form-item>
        </div>
      </a-modal>
      <ModalImg :previewImage="previewImage" ref="ModalImg"></ModalImg>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import SelectGoods from '@/components/SearchGoods/index'
import {
  getProductBatchProcessLogList,
  delProductProcessLogBatch,
  productBatchProcessLogOperate,
} from '@/api/plugin/product_traceability/productBatchProcessLog'
import NoBorderRadio from '@/components/NoBorderRadio/NoBorderRadio'

const STATUS = {
  0: '禁用',
  1: '启用',
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '产品名称',
    dataIndex: 'product_name',
  },
  {
    title: '批次名称',
    dataIndex: 'batch_name',
  },
  {
    title: '批次编号',
    dataIndex: 'batch_number',
  },
  {
    title: '流程',
    dataIndex: 'process_name',
  },
  {
    title: '操作员',
    dataIndex: 'name',
  },
  {
    title: '状态',
    dataIndex: 'state',
    scopedSlots: { customRender: 'state_status' },
  },
  {
    title: '操作时间',
    dataIndex: 'updated_at',
    scopedSlots: {
      customRender: 'updated_at',
    },
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'ProductBatchProcessLogList',
  components: {
    STable,
    NoBorderRadio,
    SelectGoods,
    ModalImg: () => import('@/components/tools/ModalImg'),
  },
  data() {
    return {
      previewImage: undefined,
      log_sheet_list: [],
      name: false,
      select_goods_visible: false,
      choosedGood: null,
      selectedRowKeys: [],
      isNew: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: 1,
      // 查询条件参数
      queryParam: {
        search_product_name_key: null,
        search_batch_name_key: null,
        search_goods_name_key: null,
        search_process_user_name_key: null,
        search_batch_number_key: null,
        dateStart: null,
        dateEnd: null,
        search_state: -1,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.queryParam.product_batch_process_id = this.product_batch_process_id
        this.queryParam.product_batch_id = this.product_batch_id
        Object.assign(parameter, this.queryParam)
        return getProductBatchProcessLogList(parameter).then((res) => {
          console.log('getProductBatchProcessLogList', res)
          //  res.state = parseInt(res.state)
          // this.$nextTick(() => {
          //   this.form.setFieldsValue(pick(res, ['product_name', 'batch_name', 'batch_number', 'process_name', 'nickname', 'state', 'updated_at',]))
          // })
          return res.data
        })
      },
    }
  },
  computed: {
    product_batch_id() {
      if (this.$route.query.product_batch_id) {
        return this.$route.query.product_batch_id
      } else {
        return 0
      }
    },
    product_batch_process_id() {
      if (this.$route.query.product_batch_process_id) {
        return this.$route.query.product_batch_process_id
      } else {
        return 0
      }
    },
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {},
  activated() {
    this.$refs.table.refresh()
  },
  methods: {
    calendarChange(date, dateString) {
      this.selectDate = date[0]
    },
    onChange(date, dateString) {
      this.queryParam.dateStart = dateString[0]
      this.queryParam.dateEnd = dateString[1]
    },
    changeTab(val) {
      if (val == 1) {
        this.$router.push({ name: 'ProductList' })
      }
      if (val == 2) {
        this.$router.push({ name: 'ProductBatchList' })
      }
      if (val == 3) {
        this.$router.push({ name: 'ProductBatchProcessLogList' })
      }
    },
    onOptionChange() {
      this.$refs.table.refresh()
    },

    handleEdit(record) {
      this.isNew = false
      this.visible = true
      this.log_sheet_list = record.log_sheet_list
      this.name = record.name
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_product_name_key: null,
        search_batch_name_key: null,
        search_goods_name_key: null,
        dateStart: null,
        dateEnd: null,
        search_state: -1,
      })
      this.$refs.table.refresh(true)
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }

        this.modalLoading = true

        productBatchEdit(values)
          .then((res) => {
            console.log(res)
            this.modalLoading = false
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success(res.msg)
              this.visible = false
              this.$refs.table.refresh()
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.modalLoading = false
          })
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.defaultCheckedKeys = []
    },
    handleDelete: function (record) {
      this.$confirm({
        title: '是否删除该条数据?',
        onOk: () => {
          const hide = this.$message.loading('删除中...', 0)
          delProductProcessLogBatch({
            id: record.id,
          })
            .then((res) => {
              hide()
              if (res.code === 0) {
                this.$message.success(res.msg)
                this.$refs.table.refresh()
              } else {
                this.$error({
                  content: res.msg,
                })
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              hide()
            })
        },
        onCancel() {},
      })
    },
    onSelectChange(val) {
      this.selectedRowKeys = val
    },

    // 批量操作员工
    allChangeStatus(e) {
      let that = this
      let text = e == 'open' ? '启用' : e == 'disabled' ? '禁用' : e == 'delete' ? '删除' : ''
      if (this.selectedRowKeys.length) {
        let type = e
        let status = e == 'open' ? 1 : e == 'disabled' ? 0 : e == 'delete' ? 1 : ''
        let param = {
          id: that.selectedRowKeys,
          type,
          status,
        }
        this.$confirm({
          title: '是否批量' + text,
          onOk() {
            that.change(param)
          },
          onCancel() {},
        })
      }
    },

    async change(param) {
      let that = this
      const res = await productBatchProcessLogOperate(param)
      if (res.code == 0) {
        this.$message.success(res.msg)
        this.$refs.table.refresh()
      }
    },

    handleProductChange(value) {
      // this.product_id = value
      this.$nextTick(() => {
        this.form.setFieldsValue({
          product_id: value,
        })
      })
    },

    selectGoodsModal() {
      this.select_goods_visible = !this.select_goods_visible
    },
    productBatchProcessList(record) {
      this.$router.push({ name: 'ProductBatchProcessList', query: { product_batch_id: record.id } })
    },
    productBatchProcessLogList(record) {
      this.$router.push({ name: 'ProductBatchProcessLogList', query: { id: record.id } })
    },
    seeImg(previewImage) {
      this.$refs.ModalImg.previewVisible = true
      this.previewImage = previewImage
    },
  },
}
</script>

<style lang="less" scoped>
.coupon-status-1,
.coupon-status-2 {
  &::before {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    background: #c6c6c6;
    border-radius: 50%;
    margin-right: 8px;
    transform: translateY(-2px);
  }
}
.coupon-status-2 {
  &::before {
    background: rgb(109, 228, 125);
  }
}

.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}

.img {
  width: 100px;
  height: 80px;
  margin: 10px;
}
.video {
  width: 100px;
  height: 80px;
  margin: 10px;
}
</style>
